package com.yctan.base.utils;

import com.yctan.base.entity.Admin;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtils {
    public static String secret;
    public static Long expire;
    public static String header;
    @Value("${conUtils.secret}")
    public void setSecret(String secret) {
        JwtUtils.secret = secret;
    }

    @Value("${conUtils.expire}")
    public void setExpire(Long expire) {
        JwtUtils.expire = expire;
    }

    @Value("${conUtils.header}")
    public void setHeader(String header) {
        JwtUtils.header = header;
    }

    /**
     * 生成token
     * @param admin
     * @return
     */
    public static String createToken(Admin admin) {
        if (admin == null || admin.getId() == null) {
            return null;
        }
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);//过期时间
        String token = Jwts.builder().setSubject("admin")
                .claim("id", admin.getId())
                .claim("supplier", admin.getSupplier().getId())
                .claim("userType", admin.getUserType())
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 获取token中注册信息
     *
     * @param token
     * @return
     */
    public static Claims getTokenClaim(String token) {
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 验证token是否过期失效
     *
     * @param expirationTime
     * @return
     */
    public static boolean isTokenExpired(Date expirationTime) {
        return expirationTime.before(new Date());
    }

    /**
     * 判断是否需要更新
     */
    public static boolean timeRemaining(String token) {
        long state = System.currentTimeMillis();
        long end = getTokenClaim(token).getExpiration().getTime();
        return (end-state)<30*60*1000;
    }

    /**
     * 获取token失效时间
     *
     * @param token
     * @return
     */
    public static Date getExpirationDateFromToken(String token) {
        return getTokenClaim(token).getExpiration();
    }

    /**
     * 获取用户名从token中
     */
    public static String getUsernameFromToken(String token) {
        return getTokenClaim(token).getSubject();
    }

    /**
     * 获取jwt发布时间
     *
     */
    public static Date getIssuedAtDateFromToken(String token) {
        return getTokenClaim(token).getIssuedAt();
    }


}